'use strict';

const BaseController = require('./base');

class ExpressOrderController extends BaseController {
  constructor(ctx) {
    super(ctx, 'expressOrder');
  }

  getPageInclude() {
    return [
      { model: this.ctx.model.LogisticsCompany, as: 'logisticsCompany' },
      { model: this.ctx.model.Warehouse, as: 'warehouse' },
      { model: this.ctx.model.ExpressOutlet, as: 'outlet' }
    ];
  }

  getListInclude() {
    return [
      { model: this.ctx.model.LogisticsCompany, as: 'logisticsCompany' },
      { model: this.ctx.model.Warehouse, as: 'warehouse' },
      { model: this.ctx.model.ExpressOutlet, as: 'outlet' }
    ];
  }

  getDetailInclude() {
    return [
      { model: this.ctx.model.LogisticsCompany, as: 'logisticsCompany' },
      { model: this.ctx.model.Warehouse, as: 'warehouse' },
      { model: this.ctx.model.ExpressOutlet, as: 'outlet' },
      { model: this.ctx.model.InsuranceCoverage, as: 'insuranceCoverage' },
      { model: this.ctx.model.User, as: 'user' },
      { model: this.ctx.model.OrderItem, as: 'orderItems' },
      { model: this.ctx.model.LogisticsTrack, as: 'logisticsTracks' }
    ];
  }

  // 创建快递订单（包含物品信息）
  async createOrder() {
    const { ctx } = this;
    const data = ctx.request.body;
    
    // 开启事务
    const transaction = await ctx.model.transaction();
    
    try {
      // 1. 创建订单
      const orderData = {
        order_no: 'EO' + Date.now() + Math.floor(Math.random() * 1000),
        sender_name: data.sender_name,
        sender_phone: data.sender_phone,
        sender_address: data.sender_address,
        receiver_name: data.receiver_name,
        receiver_phone: data.receiver_phone,
        receiver_address: data.receiver_address,
        user_id: data.user_id,
        logistics_company_id: data.logistics_company_id,
        warehouse_id: data.warehouse_id,
        outlet_id: data.outlet_id,
        insurance_coverage_id: data.insurance_coverage_id,
        total_weight: data.total_weight,
        total_volume: data.total_volume,
        freight: data.freight,
        insurance_premium: data.insurance_premium,
        total_amount: data.total_amount,
        order_status: 0, // 待发货
        payment_status: data.payment_status || 0,
        remark: data.remark
      };
      
      const order = await ctx.service.expressOrder.create(orderData, transaction);
      
      // 2. 创建订单物品
      if (data.items && data.items.length > 0) {
        for (const item of data.items) {
          await ctx.service.orderItem.create({
            order_id: order.id,
            item_id: item.item_id,
            item_name: item.item_name,
            quantity: item.quantity,
            weight: item.weight,
            volume: item.volume,
            price: item.price,
            subtotal: item.subtotal
          }, transaction);
        }
      }
      
      // 3. 创建初始物流轨迹
      await ctx.service.logisticsTrack.create({
        order_id: order.id,
        track_status: 0, // 已揽收
        track_info: '订单已创建，等待发货',
        track_location: data.warehouse_name || '系统',
        operator: ctx.session.user ? ctx.session.user.nickname : '系统'
      }, transaction);
      
      // 提交事务
      await transaction.commit();
      
      ctx.success(order, 200);
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      ctx.throw(500, error.message);
    }
  }

  // 更新订单状态
  async updateStatus() {
    const { ctx } = this;
    const { id, status, trackInfo } = ctx.request.body;
    
    if (!id) ctx.throw(400, '订单ID不能为空');
    if (status === undefined) ctx.throw(400, '订单状态不能为空');
    
    // 开启事务
    const transaction = await ctx.model.transaction();
    
    try {
      // 1. 更新订单状态
      const updateData = { order_status: status };
      
      // 根据状态更新相应的时间字段
      if (status === 1) updateData.delivery_time = new Date(); // 已发货
      if (status === 4) updateData.receive_time = new Date(); // 已签收
      if (status === 5) updateData.cancel_time = new Date(); // 已取消
      
      await ctx.service.expressOrder.update(id, updateData, transaction);
      
      // 2. 添加物流轨迹
      if (trackInfo) {
        await ctx.service.logisticsTrack.create({
          order_id: id,
          track_status: status,
          track_info: trackInfo.info || this.getDefaultTrackInfo(status),
          track_location: trackInfo.location || '系统',
          operator: ctx.session.user ? ctx.session.user.nickname : '系统'
        }, transaction);
      }
      
      // 提交事务
      await transaction.commit();
      
      ctx.success(id, 200);
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      ctx.throw(500, error.message);
    }
  }

  // 获取用户订单列表
  async getUserOrders() {
    const { ctx } = this;
    const { userId, status } = ctx.query;
    
    if (!userId) ctx.throw(400, '用户ID不能为空');
    
    const where = { user_id: userId };
    if (status !== undefined) where.order_status = status;
    
    const orders = await ctx.service.expressOrder.getUserOrders(where);
    ctx.success(orders);
  }

  // 获取订单物流轨迹
  async getTrackInfo() {
    const { ctx } = this;
    const { orderId } = ctx.query;
    
    if (!orderId) ctx.throw(400, '订单ID不能为空');
    
    const trackInfo = await ctx.service.expressOrder.getOrderTrackInfo(orderId);
    ctx.success(trackInfo);
  }

  // 根据状态获取默认的轨迹信息
  getDefaultTrackInfo(status) {
    const statusMap = {
      0: '订单已创建，等待发货',
      1: '订单已发货，正在运输中',
      2: '订单运输中，即将到达目的地',
      3: '订单已到达目的地，等待签收',
      4: '订单已签收，感谢您的使用',
      5: '订单已取消'
    };
    return statusMap[status] || '订单状态已更新';
  }
}

module.exports = ExpressOrderController;
